<template>
  <div>
    <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
    >
      <!-- 复选框 -->
      <el-table-column type="selection" width="55"></el-table-column>
      <!-- 商品信息 -->
      <el-table-column label="商品信息" width="350" align="center">
        <template slot-scope="scope">
          <div class="demo-image__preview">
            <el-link @click="goToDetailPage(scope.row)">
              <el-image
                :src="scope.row.product.productImg"
                style="width: 100px; height: 100px"
              >
              </el-image>
            </el-link>
          </div>
        </template>
      </el-table-column>
      <!-- 单价 -->
      <el-table-column label="单价" width="80" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.product.price }}</span>
        </template>
      </el-table-column>
      <!-- 店铺 -->
      <el-table-column
        prop="address"
        label="店铺"
        align="center"
        show-overflow-tooltip
      >
        新华书店
      </el-table-column>
      <!-- 移除收藏 -->
      <el-table-column label="操作" width="80" align="center">
        <template slot-scope="scope">
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="removeBookFromCollection(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import axios from "axios";
import { jwtDecode } from "jwt-decode";

export default {
  name: "UserCollection",
  data() {
    return {
      tableData: [], //记录收藏信息
      selectedProducts: [],
      // formData: {
      //   addressId: "",
      // },
      userId: "",
    };
  },
  mounted() {
    console.log("收藏夹信息：");
    this.getUserIdFromToken();
    this.findUserCollection();
  },

  methods: {
    // 获取用户 id
    getUserIdFromToken() {
      const token = localStorage.getItem("token");
      if (!token) {
        console.log("没有 token，跳转到登录页面");
        this.$router.push("/login");
        return;
      }

      try {
        console.log(token); // 输出获取到的token
        console.log(jwtDecode(token)); // 解析JWT并输出

        const decoded = jwtDecode(token); // 使用新的jwtDecode进行解析
        this.userId = decoded.userId; // 获取 userId
        console.log("用户ID:", this.userId);
      } catch (error) {
        console.error("Token 解码失败:", error);
      }
    },

    //查询收藏信息
    findUserCollection() {
      axios
        .post("/collection/searchById", {
          userId: this.userId,
        })
        // .then(function (response) { // 传统的 function 语法，这样会导致 this 指向发生变化，无法正确访问 Vue 实例的 tableData
        .then((response) => {
          // 使用箭头函数确保 this 的指向正确
          console.log("response:",response);
          let books = response.data.data.collectionList;
          console.log("收藏信息：");
          console.log(books);
          books.forEach((item) => {
            item.isCheck = false;
          });
          this.tableData = books;
        })
        .catch(function (error) {
          console.log(error);
        });
    },

    //移除收藏夹某一物品
    removeBookFromCollection(row) {
      console.log("row", row);
      let collectionId = row.collectionId;
      // console.log("", cartId);
      //发送移除信息给后端
      axios
        .post(
          "/collection/delete",
          {
            collectionId: collectionId,
          },
          {
            headers: {
              "Content-Type": "application/json", // 设置请求类型为 JSON
            },
          }
        )
        .then((res) => {
          console.log(res);
          if (res.data.code === 200) {
            if (res.data.data) {
              // isDel = true;
              // console.log(isDel);
              //根据处理结果table进行相应更新
              this.tableData = this.tableData.filter(
                (item) => item.product.productId != row.product.productId
              );
              // 显示删除成功的提示
          this.$message.success("取消收藏！");
            }
          } else {
            //直接显示后端错误信息
            return this.$message.error(res.data.message);
          }
        })
        .catch((err) => {
          console.log(err);
          this.$message.error("取消收藏失败！");
        });
    },

    //进入书籍详情页
    goToDetailPage(row) {
      // console.log(row);
      //获取书籍 id
      let product = row.product.productId;
      //前往商品详情页
      console.log("product", product);
      this.$router.push({
        path: "/product-detail",
        query: { productId: product },
      });
    },
  },
};
</script>

<style scoped>
el-table {
  width: 100%;
  height: 100%;
}
.product-info {
  display: flex;
  justify-content: space-between; /* 均匀分布 */
  align-items: center; /* 垂直居中对齐 */
  margin-bottom: 10px; /* 适当的底部间距 */
}

.product-info span {
  flex: 1; /* 每个 span 元素占据相等的宽度 */
  text-align: center; /* 让文本居中对齐 */
}
</style>